const fs = require('fs');
const path = require('path');
const Service = require('egg').Service;
class ArticleService extends Service {
  //按uuid查找文章
 async findArticleByuuid(uuid){
  try {
  const article= await this.ctx.model.Article.findOne({
    where:
    {
      uuid
    }   
   })
   return article
  }catch(error){
    return error
  }
 }
 //修改文章信息
 async updateArticle(data){
  try{
    const res=await this.ctx.model.Article.update({
      title:data.title,
      content:data.content,
      channel:data.channel,
    },{where:{uuid:data.uuid}})
    return res
  }catch(error){
    console.log(error)
  }
  
 }
  //删除文章封面
  async deleteArticlePicture(uuid){
  try{
   const article= await this.findArticleByuuid(uuid)
   if(fs.existsSync(article.picstorage)){
    fs.unlink(article.picstorage, (err) => {
      if (err) {
        console.log('文件不存在');
        throw err;
      }
    });
    return 'deletesuccss'
   }
  }
  catch(error){
  return error
  }
  }
 //获取文章封面
  async downloadPicture(uuid){
    try {
      const { app } = this;
      const filePath = path.resolve(
        app.baseDir,'app/public/articlepic', `${uuid}.png`
      );
      return filePath;
    } catch (e) {
      console.log(e);
    }
   }
    // 新增文章
    async addArticle(json) {
      const { ctx } = this;
      try {
        await ctx.model.Article.create(json);
        return '新增成功';
      } catch (error) {
        return error;
      }
    }
  // 查找作者文章
  async findUserArticle(username){
    const { ctx } = this;
    console.log(username,2222)
    try{
      const user=await ctx.model.User.findOne({
        where:{
          username
        }
      })
      // console.log(user,3333333)
      const article=await ctx.model.Article.findAll({
        where:{
          userid:user.id
        }
      })
      // console.log(article)
      return article
    }
    catch(error){
      return error
    }
  }
   
  
    
    
  }
  
  module.exports = ArticleService;